package etcd

import (
	"context"
	"encoding/json"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"time"
)
var cli *clientv3.Client

type LogEntry struct {
	Path string `json:"path"`
	Topic string `json:"topic"`
}

func Init(address string,timeout time.Duration)(err error){
	cli, err = clientv3.New(clientv3.Config{
		Endpoints:   []string{address},
		DialTimeout: timeout * time.Second,
	})
	if err != nil {
		// handle error!
		fmt.Printf("connect to etcd failed, err:%v\n", err)
		return err
	}
	fmt.Println("connect to etcd success")
	return nil
}

func Read( key string)(res []*LogEntry,err error){

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	resp, err := cli.Get(ctx, key,clientv3.WithPrefix())
	cancel()
	if err != nil {
		fmt.Printf("get from etcd failed, err:%v\n", err)
		return nil, err
	}
	for _, ev := range resp.Kvs {
		err = json.Unmarshal(ev.Value, &res)
		if err!=nil {
			fmt.Println("json error",err)
		}
		fmt.Printf("read %v\n",*res[0])
	}
	fmt.Printf("read\n")
	return res,nil
}

func  WatchConf(key string,newConfCf chan []*LogEntry)  {

	watch := cli.Watch(context.Background(), key)

	for w := range watch {
		for _, evn := range w.Events {
			fmt.Printf("env:=%v  key:=%v  v:=%v", evn, string(evn.Kv.Key), string(evn.Kv.Value))
			var newConf []*LogEntry
			if evn.Type!=clientv3.EventTypeDelete {
				err := json.Unmarshal(evn.Kv.Value, &newConf)
				if err!=nil {
					fmt.Println("error on json watch",err)
				}
			}
			newConfCf<-newConf
		}
	}
}
